package com.fintech.modules.opensearch;

import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fintech.modules.base.util.PageDataDTO;

/**
 * @author xujunqi
 * @date: 2018/1/20 14:22
 * @description: uuid Rest接口调用类
 */
@RestController
@RequestMapping("/api/search")
public class SearchRest {
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private SearchBiz biz ;
    
    @ResponseBody
    @RequestMapping(path = "/simple", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
    @ApiOperation(nickname = "simple", value = "获取流水号，默认返回字符串", notes = "bizKey为必填参数，默认为'JY'")
    public PageDataDTO search(String parmStr,String queryParam) {
        logger.info("dealwith search start parmStr:{},queryParam:{}", parmStr,queryParam);
        PageDataDTO dataDTO = new PageDataDTO();
        String str ="";
        try {
            if(StringUtils.isEmpty(parmStr)){
                return dataDTO;
            }
            
            str = biz.search(parmStr,0,5);
            dataDTO = makeupPageDataDTO(str,dataDTO);
        } catch (Exception e) {
            dataDTO.setMsg("ERROR："+e.getMessage());
            logger.error("SearchRest search error: ", e);
        }
        logger.info("dealwith search end:{}", dataDTO);
        return dataDTO;
    }
    
    @ResponseBody
    @RequestMapping(path = "/searchByPage", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
    public PageDataDTO searchByPage(String parmStr,String queryParam,String page,String limit) {
        logger.info("dealwith searchByPage start parmStr:{},queryParam:{},page:{},limit:{}", parmStr,queryParam,page,limit);
        PageDataDTO dataDTO = new PageDataDTO();
        String str ="";
        try {
            if(StringUtils.isEmpty(parmStr)){
               return dataDTO;
            }
            int start = (Integer.parseInt(page) - 1)*Integer.parseInt(limit);
            int hits =  Integer.parseInt(limit);
            str = biz.search(parmStr,start,hits);
            
            dataDTO = makeupPageDataDTO(str,dataDTO);
        } catch (Exception e) {
            dataDTO.setMsg("ERROR："+e.getMessage());
            logger.error("SearchRest searchByPage error: ", e);
        }
        logger.info(str);
        return dataDTO;
    }

    private PageDataDTO makeupPageDataDTO(String str, PageDataDTO dataDTO) {
        if(dataDTO == null)  dataDTO = new PageDataDTO();
        JSONObject json = JSONObject.parseObject(str);
        if("OK".equals(json.get("status"))){
            Object res = json.get("result");
            JSONObject resObj = JSONObject.parseObject(res.toString());
            String total = resObj.get("total").toString();
            dataDTO.setCount(total);
            JSONArray dataList = resObj.getJSONArray("items");
            dataDTO.setData(dataList);
            dataDTO.setSearchtime(resObj.get("searchtime").toString());
        }
        
        return dataDTO;
    }

    /**
     * 定义非法请求时的统一异常反馈信息
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public  PageDataDTO handleInvalidRequestError(Exception ex) {
        logger.error("search handleInvalidRequestError : ", ex);
        String errorMsg = ex.getMessage();
        if(errorMsg == null) errorMsg="null";
        errorMsg.replaceAll("[\\t\\n\\r]", "").replaceAll("[\\\\]", ".").replaceAll("\"", "");

        PageDataDTO uuidRespDTO = new PageDataDTO();
        uuidRespDTO.setMsg(errorMsg);
        return uuidRespDTO;
    }
}
